package cn.agiledata.bank.wap.action;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import cn.agiledata.bank.common.dao.TransactionTemplate;
import cn.agiledata.bank.common.service.ICommonService;
import cn.agiledata.bank.common.util.Constant;
import cn.agiledata.bank.common.util.DateUtil;
import cn.agiledata.bank.common.util.OperateUtil;
import cn.agiledata.bank.common.util.PageBean;
import cn.agiledata.bank.common.util.SecurityUtil;
import cn.agiledata.bank.common.util.StringUtil;
import cn.agiledata.bank.common.util.UniqueIdentityUtil;
import cn.agiledata.bank.common.util.WeatherUtil;
import cn.agiledata.bank.hibernateBean.Account;
import cn.agiledata.bank.hibernateBean.AccountLimit;
import cn.agiledata.bank.hibernateBean.ScoresHis;
import cn.agiledata.bank.hibernateBean.SubAccount;
import cn.agiledata.bank.hibernateBean.Transaction;
import cn.agiledata.bank.myspace.service.IMySpaceService;
import cn.agiledata.bank.scores.service.IScoresService;
import cn.agiledata.bank.scores.service.ScoresFactory;
import cn.agiledata.bank.transaction.service.GetTransaction;
import cn.agiledata.bank.transaction.service.GetTransactionImpl;
import cn.agiledata.bank.transaction.service.TransactionFactory;
import cn.agiledata.bank.wap.bean.HisAccountQueryBean;
import cn.agiledata.bank.wap.form.CommonForm;
import com.vnv.infrastructure.exception.IPBException;
import com.vnv.infrastructure.logic.IPBAppFactory;

public class TransactionAction extends WapBaseAction implements Constant {
	protected IMySpaceService getMySpaceService() throws IPBException {
		return (IMySpaceService) IPBAppFactory.getObj(IMySpaceService.MGR_ID);
	}
		/**
		 * 提现
		 * @param mapping
		 * @param form
		 * @param request
		 * @param response
		 * @return
		 * @throws IPBException
		 * @throws Exception
		 */
		public ActionForward transfer(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws IPBException, Exception {
			String bankName = (String)PropertyUtils.getSimpleProperty(form, "bankName");
			String bankNo = (String)PropertyUtils.getSimpleProperty(form, "bankNo");
			String money = (String)PropertyUtils.getSimpleProperty(form, "money");
			String payPassword = (String)PropertyUtils.getSimpleProperty(form, "payPassword");
			String subAccountId = (String)PropertyUtils.getSimpleProperty(form, "subAccountId");
			String accountId = (String)PropertyUtils.getSimpleProperty(form, "accountId");
			
			
			if(StringUtil.isStrEmpty(bankNo)) {
				return messageProcess(BANKNO_EMPTY,MAIN,form,mapping,request);
			}
			if(!StringUtil.isBankcardNo(bankNo)) {	//卡号16-32位
				return messageProcess(BANKNO_FORMAT_ERROR,MAIN,form,mapping,request);
			}
			if(StringUtil.isStrEmpty(money)) {
				return messageProcess(MONEY_EMPTY,MAIN,form,mapping,request);
			}
			if(StringUtil.isStrEmpty(payPassword)) {
				return messageProcess(PAY_PASSWORD_EMPTY,MAIN,form,mapping,request);
			}
			if(!OperateUtil.isMoney(money)) {
				return messageProcess(MONEY_FORMAT_ERROR,MAIN,form,mapping,request);
			}
			if(OperateUtil.isLowerThan(money, 0.00)) {
				return messageProcess(MONEY_NOT_LOWER_THAN_ZONE,MAIN,form,mapping,request);
			}
			payPassword = SecurityUtil.encryptoMD5String(payPassword);
			ICommonService service = getCommonService();
			Account account = service.getAccount(accountId);
			

			if(account.getPayPassword().equals(payPassword)) {  //如果支付密码正确
				
				GetTransaction getTran = new GetTransactionImpl();
				TransactionFactory tt = getTran.getTransaction(Constant.ACTION_TYPE_D);
				
				Transaction tran = new Transaction();
				tran.setActionType(service.getActionTypeById(Long.parseLong(ACTION_TYPE_D)));
				tran.setAmount(new Double(money));
				tran.setDebit(service.getSubAccount(subAccountId));
				tran.setBankSeq(new Long(bankName));
				tran.setCredit(service.getRemitAccount());
				tran.setCardNo(bankNo);
				tran.setOperSource(WAP);
				if (service.compareAccountMoney(tran.getDebit().getId().toString(),tran.getAmount()) != 0) {
					return messageProcess(BALANCE_NOT_ENOUGH,MAIN,form,mapping,request);
				}
				/**金额限制**/
				if(tran.getDebit().getAccount().getAccountType().equals(Constant.ACCOUNT_TYPE_BUYER)){
				TransactionTemplate transactionTemplate = (TransactionTemplate)IPBAppFactory.getObj("transactionTemplate");
				
				AccountLimit al = transactionTemplate.getAcctlimit(tran.getDebit().getAccount());
				
				if(transactionTemplate.ifHigher(tran.getDebit().getAccount(), tran.getAmount().doubleValue(),al)){
					int tranamount;
					if(tran.getDebit().getAccount().getTranAmount()==null){
						tranamount = 0;
					}else{
						tranamount = tran.getDebit().getAccount().getTranAmount().intValue();
					}
					String err =  "提现操作失败，您单笔交易限制为"
						+al.getEachlimit()+"元，单天交易限制为"
						+al.getAlllimit()+"元，单天交易笔数限制为"+al.getTranamount().intValue()+"笔,您今天已经提现了"+tranamount+"笔，共"
						+tran.getDebit().getAccount().getSumAmount().doubleValue()
						+"元，本笔交易额为"+tran.getAmount().doubleValue()
						+"元。本次交易超过了限制";
					return messageForward(err,MAIN,form,mapping,request);
				}}
				/**金额限制**/
				/** 您的此笔款项未经过交易，不能提现。 **/
				if (!service.isValidAmount(account, money)) {
					return messageProcess(CAN_NOT_TRANSFER,MAIN,form,mapping,request);
				}
				UniqueIdentityUtil uiu = new UniqueIdentityUtil();
				tran.setTransId(uiu.getTransactionSequence(
						Constant.ACCOUNT_TYPE_BUYER,
						Constant.MODEL_TYPE_GAINMONEY));
				// 封装插入日期和修改日期
				WeatherUtil.fillCreateAndUpdateInfo(tran, accountId);
				tran.setPersonName(account.getName());
				tran.setBeginDate(new Date());
				tran.setEndDate(new Date());
				tran.setTransStatus(Constant.TRANS_STATUS_TRANSACTIONSUCCESS);
				tt.saveTransaction(tran);
				/*交易完成，更新累积的交易金额和次数*/
				Account acct = tran.getDebit().getAccount();
				acct.setSumAmount(new Double(acct.getSumAmount().doubleValue()+tran.getAmount().doubleValue()));
				if(acct.getTranAmount()==null){
					acct.setTranAmount(new Double(1));
				}else{
					acct.setTranAmount(new Double(acct.getTranAmount().doubleValue()+1));
				}
				getMySpaceService().updateAccount(acct);
				/*交易完成，更新累积的交易金额和次数*/
				/**加积分**/
				String scoresSource = null;
				
				scoresSource = Constant.SCORES_SOURCE_C;

				IScoresService iss = ScoresFactory.getScoresService();
//				根据交易金额计算积分
				ScoresHis sh = new ScoresHis();
				sh = iss.saveScoresHistory(accountId, 
						iss.getScoresRule(scoresSource, accountId),
						tran, null);
				/**加积分**/
				return messageProcess(TRANSFER_SUCCESS,MAIN,form,mapping,request);
			} else {
				return messageProcess(PAY_PASSWORD_ERROR,MAIN,form,mapping,request);
			}
			
		}
		
		/**
		 * wap银行付款
		 * @param mapping
		 * @param form
		 * @param request
		 * @param response
		 * @return
		 * @throws IPBException
		 * @throws Exception
		 */
		public ActionForward bankpayment(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws IPBException, Exception {
			String name = (String)PropertyUtils.getSimpleProperty(form, "name");
			String bankName = (String)PropertyUtils.getSimpleProperty(form, "bankName");
			String bankNo = (String)PropertyUtils.getSimpleProperty(form, "bankNo");
			String money = (String)PropertyUtils.getSimpleProperty(form, "money");
			String payPassword = (String)PropertyUtils.getSimpleProperty(form, "payPassword");
			String subAccountId = (String)PropertyUtils.getSimpleProperty(form, "subAccountId");
			String accountId = (String)PropertyUtils.getSimpleProperty(form, "accountId");
			
			if(StringUtil.isStrEmpty(name)) {
				return messageProcess(USERNAME_EMPTY,MAIN,form,mapping,request);
			}			
			if(StringUtil.isStrEmpty(bankNo)) {
				return messageProcess(BANKNO_EMPTY,MAIN,form,mapping,request);
			}
			if(!StringUtil.isBankcardNo(bankNo)) {	//卡号16-32位
				return messageProcess(BANKNO_FORMAT_ERROR,MAIN,form,mapping,request);
			}
			if(StringUtil.isStrEmpty(money)) {
				return messageProcess(MONEY_EMPTY,MAIN,form,mapping,request);
			}
			if(StringUtil.isStrEmpty(payPassword)) {
				return messageProcess(PAY_PASSWORD_EMPTY,MAIN,form,mapping,request);
			}
			if(!OperateUtil.isMoney(money)) {
				return messageProcess(MONEY_FORMAT_ERROR,MAIN,form,mapping,request);
			}
			if(OperateUtil.isLowerThan(money, 0.00)) {
				return messageProcess(MONEY_NOT_LOWER_THAN_ZONE,MAIN,form,mapping,request);
			}
			payPassword = SecurityUtil.encryptoMD5String(payPassword);
			ICommonService service = getCommonService();
			Account account = service.getAccount(accountId);
			if(account.getPayPassword().equals(payPassword)) {  //如果支付密码正确	
				GetTransaction getTran = new GetTransactionImpl();
				TransactionFactory tt = getTran.getTransaction(Constant.ACTION_TYPE_G);
				
				Transaction tran = new Transaction();
				tran.setActionType(service.getActionTypeById(Long.parseLong(ACTION_TYPE_G)));
				tran.setAmount(new Double(money));
				tran.setDebit(service.getSubAccount(subAccountId));
				tran.setBankSeq(new Long(bankName));
				tran.setCredit(service.getRemitAccount());
				tran.setCardNo(bankNo);
				tran.setOperSource(WAP);
				if (service.compareAccountMoney(tran.getDebit().getId().toString(),tran.getAmount()) != 0) {
					return messageProcess(BALANCE_NOT_ENOUGH,MAIN,form,mapping,request);
				}
				/**金额限制**/
				TransactionTemplate transactionTemplate = (TransactionTemplate)IPBAppFactory.getObj("transactionTemplate");
				
				AccountLimit al = transactionTemplate.getAcctlimit(tran.getDebit().getAccount());
				
				if(transactionTemplate.ifHigher(tran.getDebit().getAccount(), tran.getAmount().doubleValue(),al)){
					int tranamount;
					if(tran.getDebit().getAccount().getTranAmount()==null){
						tranamount = 0;
					}else{
						tranamount = tran.getDebit().getAccount().getTranAmount().intValue();
					}
					String err =  "提现操作失败，您单笔交易限制为"
						+al.getEachlimit()+"元，单天交易限制为"
						+al.getAlllimit()+"元，单天交易笔数限制为"+al.getTranamount().intValue()+"笔,您今天已经提现了"+tranamount+"笔，共"
						+tran.getDebit().getAccount().getSumAmount().doubleValue()
						+"元，本笔交易额为"+tran.getAmount().doubleValue()
						+"元。本次交易超过了限制";
					return messageForward(err,MAIN,form,mapping,request);
				}
				/**金额限制**/
				UniqueIdentityUtil uiu = new UniqueIdentityUtil();
				tran.setTransId(uiu.getTransactionSequence(
						Constant.ACCOUNT_TYPE_BUYER,
						Constant.MODEL_TYPE_PAYMONEY));
				// 封装插入日期和修改日期
				WeatherUtil.fillCreateAndUpdateInfo(tran, accountId);
				tran.setPersonName(name);
				tran.setBeginDate(new Date());
				tran.setEndDate(new Date());
				tran.setTransStatus(Constant.TRANS_STATUS_TRANSACTIONSUCCESS);
				tt.saveTransaction(tran);
				/*交易完成，更新累积的交易金额和次数*/
				Account acct = tran.getDebit().getAccount();
				acct.setSumAmount(new Double(acct.getSumAmount().doubleValue()+tran.getAmount().doubleValue()));
				if(acct.getTranAmount()==null){
					acct.setTranAmount(new Double(1));
				}else{
					acct.setTranAmount(new Double(acct.getTranAmount().doubleValue()+1));
				}
				getMySpaceService().updateAccount(acct);
				/*交易完成，更新累积的交易金额和次数*/
				/**加积分**/
				String scoresSource = null;
				
				scoresSource = Constant.SCORES_SOURCE_C;

				IScoresService iss = ScoresFactory.getScoresService();
//				根据交易金额计算积分
				ScoresHis sh = new ScoresHis();
				sh = iss.saveScoresHistory(accountId, 
						iss.getScoresRule(scoresSource, accountId),
						tran, null);
				/**加积分**/
				return messageProcess(PAY_SUCCESS,MAIN,form,mapping,request);
			} else {
				return messageProcess(PAY_PASSWORD_ERROR,MAIN,form,mapping,request);
			}

		}
		
		/**
		 * wap账户付款
		 * @param mapping
		 * @param form
		 * @param request
		 * @param response
		 * @return
		 * @throws IPBException
		 * @throws Exception
		 */
		public ActionForward vnvpayment(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws IPBException, Exception {
			String name = (String)PropertyUtils.getSimpleProperty(form, "name");
			if(!StringUtil.isStrEmpty(name)) {
				name = name.toLowerCase();
			}
			String money = (String)PropertyUtils.getSimpleProperty(form, "money");
			String payPassword = (String)PropertyUtils.getSimpleProperty(form, "payPassword");
			
			String subAccountId = (String)PropertyUtils.getSimpleProperty(form, "subAccountId");
			String accountId = (String)PropertyUtils.getSimpleProperty(form, "accountId");
			ICommonService service = getCommonService();
			Account account = service.getAccount(accountId);
			
			if(StringUtil.isStrEmpty(name)) {
				return messageProcess(USERNAME_EMPTY,MAIN,form,mapping,request);
			}			
			if(StringUtil.isStrEmpty(money)) {
				return messageProcess(MONEY_EMPTY,MAIN,form,mapping,request);
			}
			if(StringUtil.isStrEmpty(payPassword)) {
				return messageProcess(PAY_PASSWORD_EMPTY,MAIN,form,mapping,request);
			}
			if(!OperateUtil.isMoney(money)) {
				return messageProcess(MONEY_FORMAT_ERROR,MAIN,form,mapping,request);
			}
			if(OperateUtil.isLowerThan(money, 0.00)) {
				return messageProcess(MONEY_NOT_LOWER_THAN_ZONE,MAIN,form,mapping,request);
			}
			Account peerAccount = WeatherUtil.getAccountByEmail(name);
			if(peerAccount == null) { //如果对方账户不存在
				return messageProcess(PEER_ACCOUNT_NOT_EXIST,MAIN,form,mapping,request);
			}
			payPassword = SecurityUtil.encryptoMD5String(payPassword);
			if(account.getPayPassword().equals(payPassword)) {  //如果支付密码正确	
				Transaction tran = new Transaction();
				tran.setDebit(service.getSubAccount(subAccountId));  //付款方
				tran.setCredit(peerAccount.getDefaultSubAccount()); //收款方,至默认子账户
				tran.setActionType(service.getActionTypeById(Long.parseLong(Constant.ACTION_TYPE_C)));
				tran.setAmount(new Double(money)); //交易金额
				WeatherUtil.fillCreateAndUpdateInfo(tran,accountId); //封装插入日期和修改日期
				tran.setPersonName(name);
				tran.setBeginDate(new Date());
				tran.setEndDate(new Date());
				tran.setTradeType(TRADE_TYPE_NOASSURE); //无担保交易
				tran.setTransStatus(TRANS_STATUS_TRANSACTIONSUCCESS);
				tran.setOperate(MODEL_TYPE_PAYMONEY);
				tran.setOperSource(WAP);
				UniqueIdentityUtil uiu = new UniqueIdentityUtil();
				tran.setTransId(uiu.getTransactionSequence(Constant.ACCOUNT_TYPE_BUYER,Constant.MODEL_TYPE_GATHERING));
				if (service.compareAccountMoney(tran.getDebit().getId().toString(),tran.getAmount()) != 0) {
					return messageProcess(BALANCE_NOT_ENOUGH,MAIN,form,mapping,request);
				}
				//付款操作失败您选择的交易双方重复
				if(accountId.equals(peerAccount.getId().toString())) {
					return messageProcess(SAME_PERSON,MAIN,form,mapping,request);
				}
				GetTransaction getTran = new GetTransactionImpl();
				TransactionFactory tt = getTran.getTransaction(Constant.ACTION_TYPE_C);
				tt.saveTransaction(tran);
				return messageProcess(PAY_SUCCESS,MAIN,form,mapping,request);
			} else {
				return messageProcess(PAY_PASSWORD_ERROR,MAIN,form,mapping,request);
			}
			
		}
		
		/**
		 * wap历史交易查询
		 * @param mapping
		 * @param form
		 * @param request
		 * @param response
		 * @return
		 * @throws IPBException
		 * @throws Exception
		 */
		public ActionForward dealcheck(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws IPBException, Exception {
			String startDateForm = (String)PropertyUtils.getSimpleProperty(form, "startDate");
			String endDateForm = (String)PropertyUtils.getSimpleProperty(form, "endDate");
			
			String dateFormat ="yyyyMMdd HH:mm:ss";
			Date startDate = null;
			Date endDate = null;
			if(!StringUtil.isStrEmpty(startDateForm)) {
				startDate = DateUtil.string2Date(startDateForm+" 00:00:00",dateFormat);
				if(startDate == null) {
					return messageProcess(DATE_FORMAT_ERROR,MAIN,form,mapping,request);
				}
			
			}
			if(!StringUtil.isStrEmpty(endDateForm)) {
				endDate = DateUtil.string2Date(endDateForm+" 23:59:59",dateFormat);
				if(endDate == null) {
					return messageProcess(DATE_FORMAT_ERROR,MAIN,form,mapping,request);
				}
			}
			ICommonService service = getCommonService();
			HisAccountQueryBean bean = new HisAccountQueryBean();
			bean.setAccountId((String)PropertyUtils.getSimpleProperty(form, "accountId"));
			bean.setSubAccountId((String)PropertyUtils.getSimpleProperty(form, "subAccountId"));
			bean.setStartPage((String)PropertyUtils.getSimpleProperty(form, "startPage"));
			bean.setStartDate(startDate);
			bean.setEndDate(endDate);
			PageBean pb = service.getHisAccountQueryPagingList(bean);
			request.setAttribute("list",pb);
			request.setAttribute("accountId",(String)PropertyUtils.getSimpleProperty(form, "accountId"));
			request.setAttribute("subAccountId",(String)PropertyUtils.getSimpleProperty(form, "subAccountId"));
			request.setAttribute("startDate",(String)PropertyUtils.getSimpleProperty(form, "startDate"));
			request.setAttribute("endDate",(String)PropertyUtils.getSimpleProperty(form, "endDate"));
			return mapping.findForward(SUCCESS);
		}
		
		/**
		 * 
		 * @param mapping
		 * @param form
		 * @param request
		 * @param response
		 * @return
		 * @throws IPBException
		 * @throws Exception
		 */
		public ActionForward getAccountBalance(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws IPBException, Exception {
			CommonForm theForm = new CommonForm();
			theForm.setAccountId(request.getParameter("accountId"));
			theForm.setSubAccountId(request.getParameter("subAccountId"));
			ICommonService service = getCommonService();
			SubAccount subAccount = service.getSubAccount(theForm.getSubAccountId());
			
			return messageForward("余额:"+subAccount.getAccountBalance().getBalance().toString(),MAIN,theForm,mapping,request);
		}
}
